package com.example.myapp.views;

import android.content.Context;
import android.opengl.GLSurfaceView;
import android.view.MotionEvent;
import com.example.myapp.event.EventHandler;
import com.example.myapp.event.RequestRenderEvent;
import com.example.myapp.event.RequestRenderEventListener;
import com.example.myapp.render.CustomRenderer;

public class CustomGLSurfaceView extends GLSurfaceView implements RequestRenderEventListener{

    private final CustomRenderer mRenderer;

    public CustomGLSurfaceView(Context context) {
        super(context);

        setEGLContextClientVersion(2);
        mRenderer = new CustomRenderer();
        setRenderer(mRenderer);
        setRenderMode(GLSurfaceView.RENDERMODE_WHEN_DIRTY);

        EventHandler.register(this, RequestRenderEvent.class);

        requestRender();
    }

//    private final float TOUCH_SCALE_FACTOR = 180.0f / 320;
//    private float mPreviousX;
//    private float mPreviousY;

    public void handleChanges(int[] stateMatrix) {
        mRenderer.handleStateMatrix(stateMatrix);

        requestRender();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        float x = event.getX();
        float y = event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_MOVE:
                requestRender();
                break;
            case MotionEvent.ACTION_DOWN:
                mRenderer.handleDownEvent(x / this.getWidth(), y / this.getHeight());
                break;
            case MotionEvent.ACTION_UP:
                mRenderer.handleUpEvent(x / this.getWidth(), y / this.getHeight());
                break;
            default:
                break;
        }

//        mPreviousX = x;
//        mPreviousY = y;
        return true;
    }

    @Override
    public void onRequestRender(RequestRenderEvent event) {
        requestRender();
    }
}
